<template>
  <div class="flex form-border">
    <div>
      <div class="title info-deep">邀请链接</div>
      <el-input ref="joinUrl" :value="joinUrl" readonly :disabled="loading" class="m-t-8 m-b-10" />
      <el-button size="small" type="primary" @click="copyLink" :disabled="loading || !joinKey">
        复制链接
      </el-button>
      <el-button size="small" @click="resetKey" :loading="loading">
        重置链接与邀请码
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';

export default {
  name: 'invitation', // 群组邀请
  data() {
    return {
      loading: false,
    };
  },
  computed: {
    ...mapState({ curGroup: 'currentGroup' }),
    joinKey() { return this.curGroup.joinKey; },
    joinUrl() {
      const { href } = this.$router.resolve(`/groups/join/${this.joinKey}`);
      return this.joinKey ? `${location.origin}/${href}` : '邀请链接已失效，请重新生成';
    },
  },
  methods: {
    ...mapActions({ setCurGroup: 'setCurrentGroup' }),
    // 重置邀请码
    resetKey() {
      if (this.joinKey) {
        this.$confirm('重置链接后，现有邀请码和邀请链接均会失效，确认重置吗？', '提示', {
          customClass: 'confirm-left',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => this.resetKeyFn())
          .catch(() => {});
      } else this.resetKeyFn();
    },
    resetKeyFn() {
      this.loading = true;
      this.$api.groups.resetKey({ groupId: this.curGroup.id })
        .then((res) => {
          this.$message.success('重置成功');
          this.setCurGroup(Object.assign({}, this.curGroup, { joinKey: res.data.key }));
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 复制链接
    copyLink() {
      this.$copyText(this.joinUrl)
        .then(() => this.$message.success('已复制到剪切板'))
        .catch(() => this.$message.error('复制失败'));
    },
    copyKey() {
      this.$copyText(this.joinKey)
        .then(() => this.$message.success('已复制到剪切板'))
        .catch(() => this.$message.error('复制失败'));
    },
  },
};
</script>

<style></style>
